package com.example.servlettemplate.util;

import java.sql.*;
import java.util.List;

//定义数据库封装类
public class DBUtil {
    private static final String url = "jdbc:mysql://localhost:3306/servlettemplate?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true";
    private static final String username = "root";
    private static final String password = "123456";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //打开连接
    public static Connection open() {
        try {
            Connection conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //预编译SQL语句
    public static PreparedStatement pstmt(String sql, List param, Connection conn) {
        try {
            PreparedStatement stmt = conn.prepareStatement(sql);
            if (param != null) {
                for (int i = 0; i < param.size(); i++) {
                    stmt.setObject(i + 1, param.get(i));
                }
            }
            return stmt;
    }catch(Exception e) {
        e.printStackTrace();
    }
        return null;
}


    //关闭连接
    public  static  void closeAll(Connection conn, PreparedStatement stmt, ResultSet rs){
        try {
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //更新
    public static int executeUpdate(String sql, List param) {
        PreparedStatement stmt = null;
        Connection conn = null;

        try {
            conn = DBUtil.open();
            stmt = pstmt(sql, param, conn);
            return stmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(conn, stmt, null);
        }
        return 0;//返回0表示更新失败
    }
}
